package com.lykj.llw.box.ui.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ViewUtils.runOnUiThread
import com.bytedance.applog.game.GameReportHelper
import com.dinuscxj.itemdecoration.LinearDividerItemDecoration
import com.lykj.lib_base.base.BaseFragment
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.agent.AgentBuyVoucherAdapter
import com.lykj.llw.box.adapter.agent.AgentVoucherAdapter
import com.lykj.llw.box.data.bean.response.agent.AgentCanBuyVoucherResponse
import com.lykj.llw.box.data.bean.response.agent.AgentMyVoucherResponse
import com.lykj.llw.box.data.bean.response.agent.AgentUserInfoResponse
import com.lykj.llw.box.data.bean.response.agent.AgentZFBPayResponse
import com.lykj.llw.box.data.entity.PayResult
import com.lykj.llw.box.databinding.FrgReuseAgentVoucherBinding
import com.lykj.llw.box.ui.diafrg.agent.AgentChooseDiaFrg
import com.lykj.llw.box.ui.diafrg.agent.AgentVoucherGiftDiaFrg
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody

/**
 * ================================================
 * frag-复用代理代金券
 * ================================================
 *
 * @author gosha
 * @date 2023/10/30-17:15
 */
class ReUseAgentVoucherFragment : BaseFragment() {
    lateinit var binding: FrgReuseAgentVoucherBinding

    private val mBuyAdapter = AgentBuyVoucherAdapter()
    private val mBuyData = ArrayList<AgentCanBuyVoucherResponse.DataDTO>()

    private val mAdapter = AgentVoucherAdapter()
    private val mData = ArrayList<AgentMyVoucherResponse.DataDTO>()

    private var mType: Int? = 0

    private var pageSize = 10
    private var totalPage = 1
    private var pageNo = 1

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FrgReuseAgentVoucherBinding.inflate(layoutInflater)
        initUI()
        initData()
        setListener()
        return binding.root
    }

    override fun initUI() {
        //type 0:购买 1:我的代金券
        mType = arguments?.getInt("type", 0)

        initRecyclerView()

        FlowBus.with<String>("refresh_voucher").register(requireActivity()) {
            mData.clear()
            mAdapter.notifyDataSetChanged()
            obtainMyVoucher()
        }
    }

    override fun onResume() {
        super.onResume()

        if (mType != 0) {
            mData.clear()
            mAdapter.notifyDataSetChanged()
            obtainMyVoucher()
        }
    }

    private fun initRecyclerView() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvVoucher.layoutManager = linearLayoutManager
        binding.rcvVoucher.setHasFixedSize(true)
        val dividerItemDecoration = LinearDividerItemDecoration(
            requireContext(), LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setDivider(
            resources.getDrawable(
                R.drawable.divider_0dp, resources.newTheme()
            )
        )
        binding.rcvVoucher.addItemDecoration(dividerItemDecoration)
        val emptyView = View.inflate(requireContext(), R.layout.empty_playing, null)
        emptyView.findViewById<TextView>(R.id.tv_desc).text = "暂无代金券"

        if (mType == 0) {
            mBuyAdapter.setEmptyView(emptyView)
            mBuyAdapter.data = mBuyData
            mBuyAdapter.addChildClickViewIds(R.id.tv_btn_pay)
            mBuyAdapter.setOnItemChildClickListener { _, view, position ->
                if (view.id == R.id.tv_btn_pay) {
                    //支付
                    buy(mBuyData[position].id, mBuyData[position].couponPrice)
                }
            }
            binding.rcvVoucher.adapter = mBuyAdapter
        } else {
            mAdapter.setEmptyView(emptyView)
            mAdapter.data = mData
            mAdapter.addChildClickViewIds(R.id.tv_btn_send)
            mAdapter.setOnItemChildClickListener { _, view, position ->
                if (view.id == R.id.tv_btn_send) {
                    //赠送选择
                    AgentChooseDiaFrg()
                        .setCouponId(mData[position].id)
                        .setCouponMoney(mData[position].couponMoney)
                        .show(childFragmentManager, "赠送选择弹窗")
                }
            }
            binding.rcvVoucher.adapter = mAdapter
        }
    }

    private fun buy(id: Int, couponPrice: Double) {
        obtainAgentUserInfo(id, couponPrice)
    }

    //获取代理用户信息
    private fun obtainAgentUserInfo(id: Int, couponPrice: Double) {
        RetrofitManager.instance.obtainAgentInfo(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@ReUseAgentVoucherFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, AgentUserInfoResponse::class.java)

                //判断余额是否够使用
                if (bean.data.money >= couponPrice) {
                    //余额购买
                    balanceBuy(id)
                } else {
                    //支付宝购买
                    zfbBuy(id)
                }
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(requireContext(), it)
                }
            }
        })
    }

    //余额购买
    private fun balanceBuy(id: Int) {
        RetrofitManager.instance.balanceBuy("$id",
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this@ReUseAgentVoucherFragment, d)
                }

                override fun specificHandle(responseBody: String) {
                    ToastUtils.showShort(requireContext(), "购买成功")
                    FlowBus.with<String>("refresh_voucher")
                        .post(requireActivity().lifecycleScope, "")
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(requireContext(), it)
                    }
                }
            })
    }

    //支付宝购买
    private fun zfbBuy(id: Int) {
        RetrofitManager.instance.zfbBuy("$id", object : CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@ReUseAgentVoucherFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, AgentZFBPayResponse::class.java)
                if (!TextUtils.isEmpty(bean.data.payUrl)) {
                    Thread {
                        val alipay = PayTask(requireActivity())
                        val result = alipay.payV2(bean.data.payUrl, true)
                        val payResult = PayResult(result)
                        val resultInfo: String? = payResult.result // 同步返回需要验证的信息
                        val resultStatus: String? = payResult.resultStatus
                        LogUtils.e("asd", "alipay: $resultInfo::$resultStatus::$payResult")
                        // 判断resultStatus 为9000则代表支付成功
                        if (TextUtils.equals(resultStatus, "9000")) {
                            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                            runOnUiThread {
                                ToastUtils.showShort(requireContext(), "支付成功")
                                FlowBus.with<String>("refresh_voucher")
                                    .post(requireActivity().lifecycleScope, "")
                            }
                        } else {
                            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                            runOnUiThread {
                                ToastUtils.showShort(requireContext(), "支付失败")
                            }
                        }
                    }.start()
                }
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(requireContext(), it)
                }
            }
        })
    }

    //获取可购买代金券
    private fun obtainCanBuyVoucher() {
        clearBodyParam()
        initBodyParam()
        bodyParams["pageNo"] = pageNo
        bodyParams["pageSize"] = pageSize
        RetrofitManager.instance.obtainCanBuyVoucher(bodyParams, object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@ReUseAgentVoucherFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, AgentCanBuyVoucherResponse::class.java)

//                totalPage = bean.data.totalPage

                if (bean.data.size > 0) {
                    mBuyData.addAll(bean.data)
                }

                mBuyAdapter.notifyDataSetChanged()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(requireContext(), it)
                }
            }
        })
    }

    //我的代金券
    private fun obtainMyVoucher() {
        clearBodyParam()
        initBodyParam()
        bodyParams["pageNo"] = pageNo
        bodyParams["pageSize"] = pageSize
        RetrofitManager.instance.obtainMyVoucher(bodyParams, object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@ReUseAgentVoucherFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, AgentMyVoucherResponse::class.java)

                // totalPage = bean.data.totalPage

                if (bean.data.size > 0) {
                    mData.addAll(bean.data)
                }

                mAdapter.notifyDataSetChanged()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(requireContext(), it)
                }
            }
        })
    }

    override fun initData() {
        if (mType == 0) {
            obtainCanBuyVoucher()
        } else {
            obtainMyVoucher()
        }
    }

    override fun setListener() {
        binding.srfRefresh.setOnRefreshListener {
            mData.clear()
            mBuyData.clear()
            mAdapter.notifyDataSetChanged()
            mBuyAdapter.notifyDataSetChanged()

            pageNo = 1
            if (mType == 0) {
                obtainCanBuyVoucher()
            } else {
                obtainMyVoucher()
            }
            it.finishRefresh(350, true, false)
            it.resetNoMoreData()
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}